import React , { useState, useEffect, useRef } from "react"
import { Toast } from 'antd-mobile';
import { queryPhoneCaptcha } from '@/services/user';
// import { queryMemberCaptcha, queryMemberCreateCaptcha } from '@/services/merchant';
import { Message } from '@/design';
import { isEmpty, checkField } from '@/utils/common';

let captchaTimedFn:any = undefined;

export default function (props:any) {

  const tempText = '獲取驗證碼';
  const spinning = useRef(false);

  const [buttonText, setButtonText] = useState(tempText);

  const handleGetCaptcha = async () => {
    // console.log(props)
    const { action, phoneAreaCode, mobileNumber, sendCaptcha = true } = props;
    // console.log(phoneAreaCode)
    if (!sendCaptcha) return false;
    let msg = checkField(`phone_${phoneAreaCode}`, mobileNumber);
    if (!isEmpty(msg)) {
      Message.error(msg);
      return false
    };
    if (spinning.current) {
      return false;
    }
    spinning.current = true;
    setButtonText('發送中…');
    let result = undefined;
    console.log('1 console.log(action)===', action)
    if (action === 'merchant-sign') {
     
      // result = await queryMemberCaptcha({ mobileAreaCode: phoneAreaCode, mobile: mobileNumber });
    }  else {
      result = await queryPhoneCaptcha({ action, phoneAreaCode, mobileNumber });
    }
    spinning.current = false;
    // console.log(result)
    if (!result) {
      setButtonText(tempText);
      return false;
    }
    localStorage.setItem('captchaTimed', '60');
    captchaTimeOut();
  }

  const captchaTimeOut = () => {
    captchaTimedFn = setTimeout(() => {
      let count = localStorage.getItem('captchaTimed') ? Number(localStorage.getItem('captchaTimed')) : 0;
      // console.log(count)
      if (count > 0) {
        setButtonText(`${count} s`);
        count--;
        localStorage.setItem('captchaTimed', `${count}`);
        captchaTimeOut();
      } else {
        setButtonText(tempText);
      }
    }, 1000);
  }

  useEffect(() => {
    captchaTimeOut();
    return () => {
      clearTimeout(captchaTimedFn);
    }
  }, [])

  useEffect(() => {
    props.sendCaptcha && handleGetCaptcha()
  }, [props.sendCaptcha])

  return <button className={props.className} type="button" disabled={buttonText !== tempText || props.disabled} onClick={handleGetCaptcha}>{buttonText}</button>
}